import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, getUserInfo } from '@/utils/api'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref(null)
  const token = ref(localStorage.getItem('token') || '')

  const loginAction = async (loginForm) => {
    try {
      const res = await login(loginForm)
      token.value = res.data.token
      localStorage.setItem('token', token.value)
      await getUserInfoAction()
      ElMessage.success('登录成功')
      return true
    } catch (error) {
      ElMessage.error(error.message || '登录失败')
      return false
    }
  }

  const getUserInfoAction = async () => {
    try {
      const res = await getUserInfo()
      userInfo.value = res.data
    } catch (error) {
      ElMessage.error('获取用户信息失败')
    }
  }

  const logout = () => {
    userInfo.value = null
    token.value = ''
    localStorage.removeItem('token')
  }

  const initUserInfo = () => {
    if (token.value) {
      getUserInfoAction()
    }
  }

  return {
    userInfo,
    token,
    loginAction,
    getUserInfoAction,
    logout,
    initUserInfo
  }
})
